package com.zj;


import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.log4j.Logger;

import java.io.PrintWriter;
import java.lang.reflect.Type;
import java.net.Socket;
import java.util.Scanner;

public class AtmClient {
    //引入日志
    private static Logger log=Logger.getLogger(AtmClient.class.getName());
    public static void main(String[] args) {
        String host="localhost";
        int port=12000;
        //创建一个socket对象
        Scanner keyword=new Scanner(System.in);
        boolean flag=true;
        try(
                //创建一个socket对象
                Socket s=new Socket(host,port);
                //利用套接字获取字节流并转换成字符流
                PrintWriter pw=new PrintWriter(s.getOutputStream());//println可以一行一行的发送
                //利用套接字获取字节流并转换成字符流
                Scanner sc=new Scanner(s.getInputStream());//读取服务器的响应 nextLine()
        ){
            log.info("连接ATM服务器成功"+s.getRemoteSocketAddress()+"连接成功");
            do{
                System.out.println("====中国银行ATM欢迎您的使用===");
                System.out.println("1.存款");
                System.out.println("2.取款");
                System.out.println("3.查询余额");
                System.out.println("4.退出");
                System.out.println("5.错误命令");
                System.out.println("=======================");
                System.out.println("请输入您的选择：");
                String command=keyword.nextLine();  //输入操作选项
                String response=null;
                if("1".equalsIgnoreCase(command)){
                    pw.println("DEPOSIT 1 100");
                }else if("2".equalsIgnoreCase(command)){
                    pw.println("WITHDRAW 1 10");
                }else if("3".equalsIgnoreCase(command)){
                    pw.println("BALANCE 1");
                }else if("5".equalsIgnoreCase(command)){
                    pw.println("abcdef");
                }else {
                    pw.println("QUIT");
                    pw.flush();
                    flag=false;
                    break;
                }
                pw.flush();
                //取服务器的响应
                response=sc.nextLine();
                System.out.println("服务器的响应："+response);
                Gson gson=new Gson();
                //设定gson 处理的字符串数据的模板  vue  axios
                Type type=new TypeToken<JsonModel<BankAccount>>(){}.getType();  //通过TypeToken获取类型
                JsonModel<BankAccount> jm=gson.fromJson(response,type);
                if (jm.getCode()==1){
                    BankAccount ba=jm.getObj();
                    System.out.println(ba.getId()+"\t"+ba.getBalance());
                }else{
                    System.out.println(jm.getErrorMsg());
                }

            }while(flag);
            System.out.println("ATM客户端已退出当前账号");
        }catch (Exception e){
            e.printStackTrace();
        }

    }




}
